﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Net;

namespace WindowsLiveWriter.TagGenerator
{
	/// <summary>
	/// Generates the tags from content, using the Yahoo Term Extractor API.
	/// </summary>
	public class TagGenerator
	{
		/// <summary>
		/// The URL of the Yahoo Term Extractor API Endpoint
		/// </summary>
		const string ADDRESS = "http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction";
		
		/// <summary>
		/// The AppID for this Plugin
		/// </summary>
		const string APP_ID = "XyICYZvV34HUrXls45VRj_n72U3XbguUp.eDKB2gvdeUp1.Q_1AQzxb5gPDF6deYujZBxMX6UmfF";

		/// <summary>
		/// Gets the tags for the specified content.
		/// </summary>
		/// <param name="content">The content.</param>
		/// <returns></returns>
		public IList<string> GetTags(string content)
		{
			// Create the web request  
			HttpWebRequest request = WebRequest.Create(ADDRESS) as HttpWebRequest;

			// Set type to POST  
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";

			// Create the data to send  
			StringBuilder data = new StringBuilder();
			data.Append("appid=" + HttpUtility.UrlEncode(APP_ID));
			data.Append("&context=" + HttpUtility.UrlEncode(content));

			// Create a byte array of the data we want to send  
			byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

			// Set the content length in the request headers  
			request.ContentLength = byteData.Length;
			request.KeepAlive = true;

			// Write data  
			using (Stream postStream = request.GetRequestStream())
			{
				postStream.Write(byteData, 0, byteData.Length);
			}

			// Get response  
			var xml = getResultXml(request);

			return getTagsFromXml(xml.Root)
				.ToList();
		}

		private XDocument getResultXml(HttpWebRequest request)
		{
			using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
			{
				XmlReader xmlReader = XmlReader.Create(response.GetResponseStream());
				XDocument xdoc = XDocument.Load(xmlReader);
				xmlReader.Close();

				return xdoc;
			}
		}
		private IEnumerable<string> getTagsFromXml(XElement root)
		{
			foreach (var x in root.Descendants())
				yield return x.Value;
		}
	}
}